<?php

namespace app\admin\controller;

use addons\wdsxh\library\Wxapp;
use app\admin\model\wdsxh\UserBelong;
use app\common\controller\Backend;
use Exception;
use PDOException;
use think\Db;
use think\exception\ValidateException;
use think\Model;

/**
 * 会员诉求
 *
 * @icon fa fa-circle-o
 */
class MemberAppeal extends Backend
{

    /**
     * MemberAppeal模型对象
     * @var \app\admin\model\MemberAppeal
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\MemberAppeal;
        $this->view->assign("isOpenList", $this->model->getIsOpenList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */



    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user','member'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids,['user','member']);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $row->images = wdsxh_full_url($row->images,true);
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $this->error('非法请求!');
    }


    /**
     * 通过
     */
    public function agree($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row->status != 0) {
            $this->error('状态错误!');
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $result = false;
            Db::startTrans();
            try {
                $params['status'] = 1;
                $params['reply_time'] = time();
                $result = $row->allowField(true)->save($params);
            } catch (ValidateException | PDOException | Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                Db::commit();
                $row = $this->model->get($ids);
                $this->sendMemberAppealResultNotice($row->toArray());
                $this->success('操作成功');
            } else {
                Db::rollback();
                $this->error(__('No rows were updated'));
            }
        }
        $this->error('非法请求!');
    }


    private function sendMemberAppealResultNotice($appeal)
    {
        ini_set('max_execution_time', '0');
        try {
            $conf = (new \app\admin\model\wdsxh\Config())->where('id', 1)->find();
            mb_internal_encoding("UTF-8");
            $data = [
                'thing2' => [
                    'value' => mb_substr($appeal['reply'], 0, 20),
                ],
                'time3' => [
                    'value' => date('Y年m月d日 H:i', $appeal['reply_time']),
                ],
                'phrase4' => [
                    'value' => '已处理',
                ]
            ];

            $userIdArray = Db::name('user')->where('status', 'normal')->column('id');
            $userWhere['user_id'] = array('in', $userIdArray);
            $userLists = (new UserBelong())->where($userWhere)->field('openid')->select();
            $users = [];
            foreach ($userLists as $row) {
                $users[] = $row['openid'];
            }
            $res = Wxapp::subscribeMessage($conf['member_appeal'], $users, '/pages/Functions/index', $data);
//            dd($res);
        } catch (\think\Exception $e) {
        }
    }


}
